package com.yan.utils;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.UUID;


import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EncryptUtil {

    /**
     * 传入文本内容，返回 SHA-256 串
     *
     * @param strText
     * @return
     */
    public String SHA256(final String strText) {
        return SHA(strText, "SHA-256");
    }

    /**
     * 传入文本内容，返回 SHA-512 串
     *
     * @param strText
     * @return
     */
    public String SHA512(final String strText) {
        return SHA(strText, "SHA-512");
    }

    public String SHA1(final String strText) {
        return SHA(strText, "SHA-1");
    }

    /**
     * 字符串 SHA 加密
     *
     * @param
     * @return
     */
    private String SHA(final String strText, final String strType) {
        // 返回值
        String strResult = null;

        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                // 创建加密对象 并傳入加密類型

                MessageDigest messageDigest = MessageDigest
                        .getInstance(strType);
                // 传入要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 類型结果
                byte byteBuffer[] = messageDigest.digest();

                // 將 byte 轉換爲 string
                StringBuffer strHexString = new StringBuffer();
                // 遍歷 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                // 得到返回結果
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }

        return strResult;
    }


    /**
     * 32位MD5加密方法 16位小写加密只需getMd5Value("xxx").substring(8, 24);即可
     *
     * @param sSecret
     * @return
     */
    public static String getMd5Value(String sSecret) {
        try {
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(sSecret.getBytes());
            int i;
            StringBuffer buf = new StringBuffer();
            byte[] b = bmd5.digest();// 加密
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static String getBase64Encoder(String param, String encoding) {
        String content = null;
        try {
            content = java.util.Base64.getEncoder().encodeToString(param.getBytes(encoding));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return content;
    }

    public static String getBase64Decoder(String param, String encoding) {

        String content = null;
        byte[] bytes = java.util.Base64.getDecoder().decode(param);

        try {
            content = new String(bytes, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return content;
    }


    /**
     * Base64 encode
     */
    public static String base64Encode(String data) {
        return org.apache.commons.codec.binary.Base64.encodeBase64String(data.getBytes());
    }

    /**
     * Base64 decode
     *
     * @throws UnsupportedEncodingException
     */
    public static String base64Decode(String data) throws UnsupportedEncodingException {
        return new String(org.apache.commons.codec.binary.Base64.decodeBase64(data.getBytes()), "utf-8");
    }

    /**
     * md5
     */
    public static String md5Hex(String data) {
        return DigestUtils.md5Hex(data);
    }

    /**
     * sha1
     */
    public static String sha1Hex(String data) {
        return DigestUtils.sha1Hex(data);
    }

    /**
     * sha256
     */
    public static String sha256Hex(String data) {
        return DigestUtils.sha256Hex(data);
    }


    /**
     * AES加密
     *
     * @param data
     * @param encKey - 密钥
     * @return
     */
    public static String aesEncrypt(String data, String encKey) {
        try {
            String algorithm = "AES";

            Key key = new SecretKeySpec(encKey.getBytes(), algorithm);
            Cipher c = Cipher.getInstance(algorithm);
            c.init(Cipher.ENCRYPT_MODE, key);

            byte[] byteContent = data.getBytes("utf-8");
            byte[] encodedValue = c.doFinal(byteContent);

            String signature = new String(org.apache.commons.codec.binary.Base64.encodeBase64(encodedValue));

            return signature;


        } catch (Exception e) {

            return null;
        }
    }


    public static String aesDecrypt(String data, String decKey) {
        SecretKey secretKey = new SecretKeySpec(decKey.getBytes(), "AES");

        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            byte[] byteContent = data.getBytes();

            byte[] cipherByte = cipher.doFinal(byteContent);

            String decryptStr = new String(cipherByte);

            return decryptStr;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }


    public static void main(String args[]) {

        EncryptUtil util = new EncryptUtil();
        System.out.println(util.SHA512("this ia a test"));
        System.out.println(util.SHA256("this is a test"));


        System.out.println(DigestUtils.sha512Hex("param").equals("ff366868b9d58a547ae8dda563f53b6977a2a83f38f69207cd272093ba38bc3915888adf11e02f73a13032532b9e20949e0158b49cd5b9add056bf4c7eeeb736"));

        String uuid = UUID.randomUUID().toString();
        String aesEncrypt = aesEncrypt("yan", "3ATJAAC8OK3J2QS7");

        System.out.println(uuid.length());

        System.out.println("====" + aesEncrypt + "  " + "3ATJAAC8OK3J2QS7".length());

        System.out.println("aesEncypt:" + aesEncrypt.equals("U2FsdGVkX182o5d4xSBa1UwHYqsSVhzYCNB3N5DtLKk="));

        System.out.println(aesDecrypt("U2FsdGVkX182o5d4xSBa1UwHYqsSVhzYCNB3N5DtLKk=", "3ATJAAC8OK3J2QS7"));




        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("SHA-512");
            md.update("param".getBytes("UTF-8"));
            String signStr = Hex.encodeHexString(md.digest());
            boolean flag = signStr.equals("ff366868b9d58a547ae8dda563f53b6977a2a83f38f69207cd272093ba38bc3915888adf11e02f73a13032532b9e20949e0158b49cd5b9add056bf4c7eeeb736");
            System.out.println(flag);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

}
